package com.five.welcome.config.websockethandler;

import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author Ywt
 */
@Component
@Slf4j
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {

    //当前连接数
    public static int onlineCount = 0;

    //存放连接信息
    private static final CopyOnWriteArraySet<WebSocketServer> WEB_SOCKET_SET
            = new CopyOnWriteArraySet<>();

    //连接会话
    private Session session;

    //接收id
    private String sid;

    //连接建立成功后的方法
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session;
        this.sid = sid;
        WEB_SOCKET_SET.add(this);
        addOnlineCount();
        log.info("有新的连接" + sid + "加入!当前在线数: " + getOnlineCount());

    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) {
        log.info("收到来自客户端：" + sid + "的信息:" + message);
        sendMessage(message, null);
    }

    //自定义发送消息
    public void sendMessage(String message, @PathParam("sid") String sid) {
        if (getOnlineCount() == 0) {
            return;
        }
        log.info("消息内容: " + message);
        for (WebSocketServer item : WEB_SOCKET_SET) {
            try {
                //如果sid为空,则发给全部
                if (sid == null) {
                    item.session.getBasicRemote().sendText(message);
                } else if (item.sid.equals(sid)) {
                    item.session.getBasicRemote().sendText(message);
                }
            } catch (IOException e) {
                log.error("消息发送失败!", e);
            }
        }
    }

    //连接关闭调用的方法
    @OnClose
    public void onClose() {
        WEB_SOCKET_SET.remove(this);
        subOnlineCount();
        log.info("有一连接关闭!当前在线数: " + getOnlineCount());
    }

    //连接错误调用的方法
    @OnError
    public void onError(Throwable error) {
        log.info("发生错误!", error);
    }

    //获取在线数
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    //在线数+1
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    //在线数-1
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}